<template>
  <div class="article-list">
    <!-- 文章列表 -->
    <van-pull-refresh :success-duration="1500" :success-text="refreshSuccessText" v-model="isreFreshLoading" @refresh="onRefresh">
    <van-list
  v-model="loading"
  :finished="finished"
  finished-text="没有更多了"
  @load="onLoad"
  :error.sync="error"
  error-text="请求失败，点击重新加载"
>
<ArticleItem v-for="(article,index) in list"
  :key="index" :article="article"></ArticleItem>
  <!-- <van-cell
  v-for="(article,index) in list"
  :key="index"
  :title="article.title"
  /> -->
    </van-list>
</van-pull-refresh>
  </div>
</template>

<script>
import { getArticles } from '@/api/article'
import ArticleItem from '@/components/article-item'
export default {
  name: 'ArticleList',
  data () {
    return {
      list: [],
      loading: false,
      finished: false,
      timestamp: null,
      error: false,
      isreFreshLoading: false,
      refreshSuccessText: '刷新成功'
    }
  },
  props: {
    channel: {
      type: Object,
      required: true
    }
  },
  methods: {
    async onLoad () {
      try {
        const { data } = await getArticles({
          channel_id: this.channel.id,
          timestamp: this.timestamp || Date.now(),
          with_top: 1
        })
        const { results } = data.data
        this.list.push(...results)
        this.loading = false
        if (results.length) {
          this.timestamp = data.data.pre_timestamp
        } else {
          this.finished = true
        }
      } catch (err) {
        // console.log('请求失败', err)
        this.error = true
        this.loading = false
      }
    },
    // 当下拉刷新的时候会触发调用该方法
    async onRefresh () {
      try {
        const { data } = await getArticles({
          channel_id: this.channel.id,
          timestamp: Date.now(),
          with_top: 1
        })
        const { results } = data.data
        this.list.unshift(...results)
        // this.list.unshift(...results)
        this.isreFreshLoading = false
        this.refreshSuccessText = `刷新成功,更新了${results.length}条数据`
      } catch (err) {
        // console.log('请求失败', err)
        this.isreFreshLoading = false
        this.refreshSuccessText = '刷新失败'
      }
      // 请求获取数据
      // 讲数据追加到列表的顶部
      // 关闭下拉刷星的 loading 状态
    }
  },
  components: {
    ArticleItem
  }
}
</script>

<style scoped lang="less">
.article-list {
  // 百分比单位是相对于父元素的
  height: 79vh;
  overflow-y: auto;
}
</style>
